import router from '@/router';
import axios from 'axios';
import { ElMessage } from 'element-plus'

export const http = axios.create({
    // 请求根路径
    baseURL: "http://ymjz.cc:8088",
    // 超时时间
    timeout: 300000,
    // 自定义请求头
    headers: { 'X-Requested-With': 'XMLHttpRequest', Authorization: (localStorage.getItem("token")) }
});

// 添加请求拦截器
http.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
http.interceptors.response.use(function (response) {
    if (response.config.url == "/captcha.jpg" || response.config.url == "/sseintoken") {
        return response.data;
    }
    if (response.data.code == 200) {
        return response.data;
    }
    else {
        console.log("[http->error]", response);
        if (response.config.headers.dlog) {
            return {};
        }
        ElMessage({
            message: response.data.msg,
            type: 'error',
        })
        return response.data
    }
}, function (error) {
    if (error.response.data.msg == 401&&localStorage.getItem("token")!=undefined) {
        ElMessage({
            message: "登录已过期",
            type: 'error',
        })
        localStorage.removeItem("token")
        router.push("/login")
    }
    return Promise.reject(error);

});